package mgoDB

import (
	"context"
	"fmt"
	"sync"

	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"go.mongodb.org/mongo-driver/x/bsonx"
)

//集合上下文
type CollectionContent struct {
	database       *mongo.Database
	databaseName   string
	collection     *mongo.Collection
	collectionName string
}

//索引记录
var indexMap = make(map[string]bool)

//锁
var look sync.Mutex

//是否创建索引
func (mgo *CollectionContent) IsCreateIndex() (c *CollectionContent, isCreate bool) {
	key := fmt.Sprint(mgo.databaseName, "#" ,mgo.collectionName)
	_, ok := indexMap[key]
	if !ok {
		look.Lock()
		defer look.Unlock()

		_, ok := indexMap[key]
		if ok {
			return mgo, false
		}
		indexMap[key] = true
		return mgo, true
	}
	return mgo, false
}

// @elems 索引集合(正序)
func (mgo *CollectionContent) SetIndex(elems []string) *CollectionContent {
	return mgo.setIndexs(elems, false, false)
}

// @elems 索引集合(倒序)
func (mgo *CollectionContent) SetIndexDesc(elems []string) *CollectionContent {
	return mgo.setIndexs(elems, false, true)
}

// @elems 索引集合
func (mgo *CollectionContent) SetUnique(elems []string) *CollectionContent {
	return mgo.setIndexs(elems, true, false)
}

// @elems 索引集合(倒序)
func (mgo *CollectionContent) SetUniqueDesc(elems []string) *CollectionContent {
	return mgo.setIndexs(elems, true, true)
}

// 设置索引
func (mgo *CollectionContent) setIndexs(elems []string, unique bool, desc bool) *CollectionContent {
	var bson = bsonx.Doc{}
	for _, val := range elems {
		if desc {
			bson = bson.Append(val, bsonx.Int32(-1))
			continue
		}
		bson = bson.Append(val, bsonx.Int32(1))
	}
	// 设置索引
	idx := mongo.IndexModel{
		Keys:    bson,
		Options: options.Index().SetUnique(unique),
	}
	//mgo.Collection.FindOne().Decode()
	_, err := mgo.collection.Indexes().CreateOne(context.Background(), idx)
	if err != nil {
		panic(err)
	}
	return mgo
}
